package com.support.base

import android.content.Context
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.support.utils.NetworkUtil
import java.lang.reflect.ParameterizedType


/**
 * 使用dataBinding的基础类
 */
abstract class DataBindingActivity<VM : OurViewModel, DB : ViewDataBinding> : BaseActivity() {

    lateinit var viewModel: VM
    lateinit var binding: DB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, bindLayout())
        binding.lifecycleOwner = this

        //获取当前对象所表示的类的超类
        val type = javaClass.genericSuperclass

        // 判断一下是否传入了泛型类型
        if (type is ParameterizedType) {

            //如果是泛型类，获取泛型的中第一个class对象，这里只有一个
            val clazz = type.actualTypeArguments[0] as Class<VM>

            //生成viewModel
            viewModel = ViewModelProvider(this).get(clazz)
        } else {
            throw Exception("每个页面必须有对应的viewModel，实在不行把BaseViewModel作为泛型传递过来")
        }

        //处理viewModel传递过来的消息(base)
        handleMsg()
        //UI初始化
        initView()
        //数据初始化
        initData()
        //初始化监听
        initListener()
    }

    protected open fun initView() {}
    protected open fun initData() {}
    protected open fun initListener() {}

    override fun onResume() {
        super.onResume()
        if (!NetworkUtil.isNetworkConnected(this)) {
            showAlert(msg = "当前网络不可用，请检查您的网络设置")
        }
    }

    /**
     * 绑定试图
     */
    abstract fun bindLayout(): Int

    /**
     * 隐藏键盘
     */
    protected open fun hideInput() {
        val imm: InputMethodManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val v = window.peekDecorView()
        if (null != v) {
            imm.hideSoftInputFromWindow(v.windowToken, 0)
        }
    }

    /**
     * 处理viewModel传递过来的消息(base)
     */
    private fun handleMsg() {
        viewModel.toastMsg.observe(this) {
            showToast(it)
        }
        viewModel.loadingMsg.observe(this) {
            showLoading(it)
        }
        viewModel.dismissLoading.observe(this) {
            dismissLoading()
        }
    }
}